package com.xian.controller;

import com.xian.pojo.Role;
import com.xian.pojo.UserInfo;
import com.xian.service.UserService;
import com.xian.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.Serializable;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController{
    // 调用userService
    @Autowired
    private UserService userService;

    // 查询全部用户
    @RequestMapping("/findAll.do")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ModelAndView findAll(){
        ModelAndView mv = new ModelAndView();
        List<UserInfo> users = userService.findAll();
        System.out.println(users);
        for (UserInfo user : users) {
            System.out.println(user.getId());
        }
        mv.addObject("userList",users);
        mv.setViewName("user-list");
        return mv;
    }
    // 添加用户
    @RequestMapping("/save.do")
    @PreAuthorize("authentication.principal.username == 'tom'")
    public String save(UserInfo userInfo){
        int i = userService.addUser(userInfo);
        return "redirect:findAll.do";
    }
    // 查询指定ID的用户
    @RequestMapping("findById.do")
    public ModelAndView findById(@RequestParam("id") String id){
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = userService.findById(id);
        mv.addObject("user",userInfo);
        mv.setViewName("user-show1");
        return mv;
    }
    // 查询用户以及可以添加的角色
    @RequestMapping("/findUserAndAddRole.do")
    public ModelAndView addRole(@RequestParam("id") String userId){
        ModelAndView mv = new ModelAndView();
        List<Role> roles = userService.findNoRole(userId);
        mv.addObject("roles",roles);
        mv.addObject("userId",userId);
        mv.setViewName("user-role-add");
        return mv;
    }

    // 给用户添加角色
    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam("userId") String userId,@RequestParam(name = "ids",required = false) String[] roleIds){
        userService.addRole(userId,roleIds);
        return "redirect:findAll.do";
    }
}
